package com.imu.purse.api.controller;

import java.sql.Timestamp;


import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.imu.common.exception.ErrorDesc;
import com.imu.common.exception.ErrorUtil;
import com.imu.common.utils.R;
import com.imu.common.validator.Assert;
import com.imu.common.validator.ValidatorUtils;
import com.imu.purse.config.GoogleAuthenticatorConfig;
import com.imu.purse.config.PhoneValidate;
import com.imu.purse.modules.app.entity.ImuUserEntity;
import com.imu.purse.modules.app.entity.ImuUserIdentityEntity;
import com.imu.purse.modules.app.form.IdentityFrom;
import com.imu.purse.modules.app.service.ImuUserIdentityService;
import com.imu.purse.modules.app.service.ImuUserService;
import com.imu.purse.modules.sms.SMSCache;
import com.imu.purse.modules.sms.SMSMessage.Type;
import com.imu.security.SessionObject;
import com.xiaoleilu.hutool.bean.BeanUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/api/identity")
@Api(tags="用户身份认证接口")
public class ApiIdentityController extends ApiAbstractController{
	
	@Autowired
	private ImuUserService imuUserService;
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	
	@Autowired
	private ImuUserIdentityService imuUserIdentityService;
	
	@Autowired
    private SMSCache cache;
	
	@PostMapping("/saveIdentity")
	@ApiOperation("保存身份证识别码")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "body",   dataType="IdentityFrom", name = "form", 		value = "转账",	  required = true),
	    	@ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SECRET",  value = "密钥",  required = true),
	        @ApiImplicitParam(paramType = "header", dataType="String",    name = "X-IMU-SESSION", value = "会话",  required = true)})
	public R saveIdentity(HttpServletRequest request,@RequestBody IdentityFrom form,@RequestHeader("X-IMU-SECRET") String secret, @RequestHeader("X-IMU-SESSION") String token){
		
		 //表单校验
        ValidatorUtils.validateEntity(form);
        /*String browserLanguage=request.getHeader("Accept-Language");
        if(browserLanguage.equals("zh-TW")){
        	browserLanguage="tw";
        }else {
        	browserLanguage=browserLanguage.substring(0, 2);//截取浏览器语言的前两位   判断是中文还是英文
		}*/
        SessionObject session = com.imu.security.SessionTokenProviderFactory.getSessionTokenProvider().getCurrent(secret, token);
        if(session==null){
        	return ErrorUtil.errorMesg(request,ErrorDesc.TOKEN_EMPTY);
        }
        	
      //验证手机验证码
        String type = String.valueOf(form.getType());
        Type messageType = PhoneValidate.Authentication(type);
        if(messageType == null) {
        	return ErrorUtil.errorMesg(request,ErrorDesc.TYPE_ERR);
        }
        try{
        	String a =cache.findCode(messageType.getType(), form.getPhone());
        	if(a!=null && ""!=a){
        		if(!a.equals(form.getCode())){
        			return ErrorUtil.errorMesg(request,ErrorDesc.ACODE_ERROR);
        		}
        	}else {
        		return ErrorUtil.errorMesg(request,ErrorDesc.ACODE_ERROR);
			}
		}
        catch (Exception e) {
        	return ErrorUtil.errorMesg(request,ErrorDesc.ACODE_ERROR);
		}
        //判断是否有该用户
        ImuUserEntity imuUser = JSON.parseObject(redisTemplate.opsForValue().get(form.getPhone()),ImuUserEntity.class);//imuUserService.queryByMobile(form.getPhone());
        if(imuUser == null){
        	return ErrorUtil.errorMesg(request,ErrorDesc.PHONE_ERR);
        }
        /*String secretStr = redisTemplate.opsForValue().get(form.getPhone() + "secret");
        if(!StringUtil.isEmpty(secretStr)){
        	return R.error(ErrorDesc.Identity_Exists.getCode(), ErrorDesc.Identity_Exists.getMsg());
        }*/
        //取前台传过来的密钥与身份识别码验证google身份认证码
        long t = System.currentTimeMillis();
        GoogleAuthenticatorConfig ga = new GoogleAuthenticatorConfig();
    	ga.setWindowSize(5); 
    	boolean r = ga.check_code(form.getSecretKey(), Long.parseLong(form.getSafeCode()), t);
    	if(!r){
    		return ErrorUtil.errorMesg(request,ErrorDesc.Identity_Iuthentication_Code);
    	}
       //如果验证通过  则将当前密钥保存到缓存  当前用户id为key
    	redisTemplate.opsForHash().put("googleQrCode", form.getPhone(),form.getSecretKey());
        //查询ImuUserIdentityEntity是否当前用户已经存了密钥   如果存在则update
    	ImuUserIdentityEntity entity = new ImuUserIdentityEntity();
    	entity.setUserId(Long.parseLong(session.getId()));
    	entity = imuUserIdentityService.selectByUserId(entity);
    	Timestamp nowTime = new Timestamp(System.currentTimeMillis());
    	if(null==entity){
    		entity = new ImuUserIdentityEntity();
            BeanUtil.copyProperties(form, entity);
            entity.setUserId(imuUser.getId());
            entity.setCreateTime(nowTime);
            entity.setUpdateTime(nowTime);
            imuUserIdentityService.saveData(entity);
    	}else {
    		entity.setSecretKey(form.getSecretKey());
    		imuUserIdentityService.update(entity);
		}
    	//删除缓存中之前的验证码
		cache.delCode(messageType.getType(),imuUser.getPhone());
        return R.ok(1);
	}
	
	/**
	 * 相当于重新给一个新的密钥以及二维码
	 * @param phone
	 * @param secret
	 * @param token
	 * @return
	 */
	@GetMapping("/delIdentity/{phone}")
	@ApiOperation("删除身份识别码")
	public R delIdentity(HttpServletRequest request,@PathVariable("phone")String phone,@RequestHeader("X-IMU-SECRET") String secret, @RequestHeader("X-IMU-SESSION") String token){
		
		SessionObject session = com.imu.security.SessionTokenProviderFactory.getSessionTokenProvider().getCurrent(secret, token);
		if(session==null){
			return ErrorUtil.errorMesg(request,ErrorDesc.TOKEN_EMPTY);
		}
		//删除对应缓存中密钥信息
		redisTemplate.opsForHash().delete("googleQrCode",phone);
		//删除数据库该用户身份信息
		imuUserIdentityService.delByUserId(Long.valueOf(session.getId()));
		//已上是返回新密钥的信息
		String secrets = GoogleAuthenticatorConfig.generateSecretKey();
		//删除缓存中密钥

    	return R.ok(1).put("secretFlag", 0).put("QrCode", secrets);
	}
	/**
	 * 身份识别码应该先查询是否已经保存了密钥
	 * @param phone
	 * @param secret
	 * @param token
	 * @return
	 */
	@GetMapping("/findIdentity/{phone}")
	@ApiOperation("查找身份识别码")
	public R findIdentity(HttpServletRequest request,@PathVariable("phone")String phone,@RequestHeader("X-IMU-SECRET") String secret, @RequestHeader("X-IMU-SESSION") String token){
    	Assert.isBlank(phone, ErrorDesc.PHONE_EMPTY.getMsg(), ErrorDesc.PHONE_EMPTY.getCode());
    	//String browserLanguage=request.getHeader("Accept-Language");
		SessionObject session = com.imu.security.SessionTokenProviderFactory.getSessionTokenProvider().getCurrent(secret, token);
		if(session==null){
			return ErrorUtil.errorMesg(request,ErrorDesc.TOKEN_EMPTY);
		}
        //判断是否有该用户
        ImuUserEntity imuUser = JSON.parseObject(redisTemplate.opsForValue().get(phone),ImuUserEntity.class);//imuUserService.queryByMobile(phone);
        if(imuUser == null){
        	return ErrorUtil.errorMesg(request,ErrorDesc.PHONE_ERR);
        }
        //1.获取当前用户是否已经保存了密钥  如果保存了   就返回当前密钥   如果没返回就返回一个新的密钥 并分别做标记
        Object QrCode = redisTemplate.opsForHash().get("googleQrCode", phone);
        if(null!=QrCode){//证明已经有了密钥
        	return R.ok(1).put("secretFlag", 1).put(" ", "******");
        }else {
        	String secrets = GoogleAuthenticatorConfig.generateSecretKey();  
        	return R.ok(1).put("secretFlag", 0).put("QrCode", secrets);
		}
	}
	
}
